package com.ng.desktop.view.receta;

import javax.swing.JOptionPane;

import com.ng.desktop.model.Alimento;
import com.ng.desktop.model.Receta;
import com.ng.desktop.persistence.RecetaPersistence;
import com.ng.framework.view.desktop.NGEntitySelectorField;
import com.ng.framework.view.desktop.NGTablePanel;

public class RecetaTablePanel extends NGTablePanel<Receta, RecetaPersistence> {

	private static final long serialVersionUID = 7355770232494743166L;

	public RecetaTablePanel(RecetaPersistence persistence) {
		super(persistence);
	}

	public RecetaTablePanel(RecetaPersistence persistence, NGEntitySelectorField<Receta, RecetaPersistence> ngEntitySelectorField) {
		super(persistence, ngEntitySelectorField);
	}

	@Override
	protected String[] getColumnNames() {
		return new String[]{"Id", "Nombre", "Alimentos"};
	}

	@Override
	protected int[] getColumnWidths() {
		return new int[]{70, 165, 320};
	}

	@Override
	protected Object[] toRow(Receta dataObject) {
		StringBuilder alimentos = new StringBuilder();
		for (Alimento alimento : dataObject.getAlimentos()) {
			if (alimentos.length() > 0) {
				alimentos.append(", ");
			}
			if (alimento != null) {
				alimentos.append(alimento.getNombre());
			}

		}

		return new Object[]{dataObject.getId(), dataObject.getNombre(), alimentos};
	}

	@Override
	protected boolean create(RecetaPersistence persistence) {
		RecetaEditDialog dialog = new RecetaEditDialog(JOptionPane.getFrameForComponent(this), persistence);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected boolean edit(RecetaPersistence persistence, Receta instance) {
		RecetaEditDialog dialog = new RecetaEditDialog(JOptionPane.getFrameForComponent(this), persistence, instance);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected Receta getSelectedInstance(RecetaPersistence persistence, Object[] rowData) {
		return persistence.findById((Long) rowData[0]);
	}

}
